//
//  SettingView.swift
//  taxiDriver
//
//  Created by 恒  王 on 2023/12/8.
//

import SwiftUI
import AlertToast
import Foundation

struct SettingView: View {
    @State var needInputPassengerInfo = false // 是否弹出个人信息输入框
    @Binding var passengerInfo : PassengerInput
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    @State var showAbout = false
    @State var needAbout = false // About us
    
    @State  var sourceList : [Todo] = []
    
    @State private var versionShowToast = false //版本号弹框
    @State var needLanguage = false // 是否弹出语言选择窗口
    @State private var show = false
    @State private var errorShow = false
    @State private var errorStr = ""
    @State private var successShow = false
    @State private var successShowCopy = false
    
    @State private var loginOut = false
    @State private var servicePhone : String = ""
    @State private var serviceWechat : String = ""
//    @State var appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate

    var body: some View {
        NavigationView {
            GeometryReader { geometry in
                VStack( content: {
                    
                    SettingHeaderView(geometry: geometry, presentationMode: presentationMode)
                    List() {
                        Section(header: Text("常用工具").foregroundColor(.black).padding(.horizontal,15).font(.system(size: 16,weight: .bold)).frame(height:40).frame(maxWidth:.infinity,alignment: .leading),
                                footer: EmptyView()) {
                            ForEach(sourceList, id:\.name){ (todo) in
                                
                                if !todo.push {
                                    SettingCellView(todo: todo, geometry: geometry)
                                        .listRowSeparator(.hidden)
                                        .contentShape(Rectangle())// 追加热区设置
                                    
                                    .onTapGesture {
                                        if todo.name == "客服电话" {
                                                print("call service phone number:\(servicePhone)")
                                                guard let number = URL(string: "tel://\(servicePhone)") else { return }
                                                UIApplication.shared.open(number)
                                            
                                        }
                                        if todo.name == "客服微信" {
                                            UIPasteboard.general.string = "\(serviceWechat)"
                                            self.successShowCopy.toggle()
                                        }
//
//                                            guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else {
//                                                          return
//                                                      }
//
//                                                      UIApplication.shared.open(settingsURL)
//                                            return
//                                        }
//                                        if todo.name == "应用设置" {
//                                           
//                                            guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else {
//                                                          return
//                                                      }
//                                                      
//                                                      UIApplication.shared.open(settingsURL)
//                                            return
//                                        }
//                                        
//                                        if todo.name == "屏幕方向" {
//                                            
//                                            logger.info("屏幕方向")
//                                            ViewModel.shared.isChangeScren = ViewModel.shared.isChangeScren ? false : true
//                                            UIViewController.attemptRotationToDeviceOrientation()
//                                            return
//                                        }
                                        if todo.name == "乘客信息" {
                                            
//                                            self.needInputPassengerInfo.toggle()
                                            return
                                        }
                                        if todo.name == "设置语言" {
                                            
                                            self.needLanguage.toggle()
                                            return
                                        }
//                                        if todo.name == "关于我们" {
//                                            
//                                            self.needAbout.toggle()
//                                            return
//                                        }
                                        
//                                        if todo.name == "注销账号" {
//                                            
//                                            self.loginOut = true
//                                            return
//                                        }
//                                        
//                                        if todo.name == "软件版本" {
//                                            
//                                            self.versionShowToast = true
//                                            return
//                                        }
                                        
                                    }
                                } else {
                                    ZStack(alignment: .leading){
                                      
                                        
                                        VStack(spacing: 0) {
                                            HStack {
                                                Image(todo.icon)
                                                    .resizable()
                                                    .frame(width: 20,height: 20)
                                                    .aspectRatio(contentMode: .fit)
                                                
                                                self.cellTectView(for: todo)
                                                Spacer()
                                                Image("setting_right")
                                                    .resizable()
                                                    .frame(width: 10,height: 15, alignment: .trailing)
                                                    .aspectRatio(contentMode: .fit)
                                            }.padding(.horizontal,15).frame(height: 50)
//                                            Spacer()
                                            Divider()
//                                            VStack{}
//                                                .frame(width: geometry.size.width - 40 ,height: 1, alignment: .trailing)
//                                                .background(Color(hex: ColorConfig.separationColor))

                                        }.background{
                                            NavigationLink (destination:  destinationView(for:todo)){
                                               EmptyView()
                                            }
                                            .buttonStyle(StaticButtonStyle())
                                            .opacity(0.0)
                                        }
                                        .contentShape(Rectangle())// 追加热区设置
                                    }
                                    .listRowSeparator(.hidden)
                                }
                                
                            }
                        }.background(.white).listRowInsets(EdgeInsets())
                    }
                   
                    // 正确的条件编译写法
//#if canImport(SwiftUI) && swift(>=6.0)
//    // iOS 15+ 代码路径
//    .scrollDisabled(true)
//#else
//    // iOS 14 及以下的替代方案
//    .gesture(
//        DragGesture(minimumDistance: 0)
//            .onChanged { _ in }
//    )
//#endif
                .listStyle(PlainListStyle())
                .background(.white).frame(width: geometry.size.width-30,height:50*4+70)
                    Spacer()
                }).background(.linearGradient(Gradient(colors: [Color(hex: "#F8FFF8"),Color(hex: "#FCFBE4")]), startPoint: .leading, endPoint: .trailing))
                
                .toast(isPresenting: $versionShowToast, alert: {
                    let infoDictionary : [String : Any] = Bundle.main.infoDictionary!
                    let minorVersion : Any = infoDictionary["CFBundleShortVersionString"] as Any // 版本号(内部标示)
                    let str = minorVersion as! String
                    
                    return AlertToast(type: .regular, title: "V" + str)
                })
                .onAppear(){
                    
                    Task{
                        await Api.getServiceInfo{ r in
                           switch r {
                              case .success(let data):
                               logger.info("getServiceInfo result:\(data.phone) \(data.wechatAccount)")
                               
                                 DispatchQueue.main.async {
                                     
                                     self.servicePhone = data.phone.trimmingCharacters(in: .whitespacesAndNewlines)
                                     self.serviceWechat = data.wechatAccount.trimmingCharacters(in: .whitespacesAndNewlines)
                                     // 打印赋值后的值
                                         print("servicePhone 赋值: \(self.servicePhone)")
                                         print("serviceWechat 赋值: \(self.serviceWechat)")
                                         print("sourceList 第一个元素 value: \(self.sourceList.first?.value ?? "空")")
                                     
                                     print("Before update: \(self.sourceList)")
                                     var data = [
                                        Todo(icon: "kefu", name:"客服电话",url: "personal", index: 1, push: false, value:"\(self.servicePhone)"),
                                         Todo(icon: "weixin", name:"客服微信",url: "personal", index: 2, push: false, value:"\(self.serviceWechat)"),
                                         Todo(icon: "chengkexinxi", name:"乘客信息",url: "personal", index: 1, push: true , value: ""),
                                         Todo(icon: "language", name:"设置语言",url: "Call mum", index: 3, push: false, value: ""),
                                     ]
                                     self.sourceList = data;
                                     print("After update: \(self.sourceList)")
                                     
                                 }
                               

                              case .failure(let err):
                                 logger.info("getServiceInfo error:\(err.localizedDescription)")
                           }
                        }
                    }
                   
                }
                
                VStack {
                      // 语言选择
                   if self.needLanguage {
                      Spacer()
                      LanguageView(showMe:self.$needLanguage)
                         .frame(width:geometry.size.width - 40,height:260)
                         .shadow(color: Color.black.opacity(0.3), radius: 20, x: 0, y: 10)
                         .offset(x:20,y: -geometry.size.height / 2 + 130)
                   }
                }
                // MARK: 乘客信息
                if self.needInputPassengerInfo {
                    VStack(spacing: 0) {
                        // 半透明背景
                        Color.black.opacity(0.4)
                                .edgesIgnoringSafeArea(.all)

                        UserInfoView(passenger: passengerInfo, showSheet: $needInputPassengerInfo)
                        
                    }
                }
                

            }
        }
        .navigationBarHidden(true)
        .ignoresSafeArea() //<-here
        
        .toast(isPresenting: $show, alert: {
            
            return AlertToast(type: .loading, title: "")
        })
        .toast(isPresenting: $errorShow, alert: {
            
            return AlertToast(type: .error(.red), title: self.errorStr)
        })
        .toast(isPresenting: $successShowCopy, alert: {
            
            return AlertToast(type: .regular, title: String(localized: "复制成功"))
        })
        .toast(isPresenting: $successShow, alert: {
            
            return AlertToast(type: .regular, title: String(localized: "账号注销成功"))
        })
        .alert(isPresented: $loginOut) {
            
           return Alert(title: Text("注销"), message: Text("注销账号服务器将删除账号和所有数据，无法恢复，彻底删除的话请点击确定！"), primaryButton: .default(Text("取消")), secondaryButton: .default(Text("确定"), action: {
                
               self.unregistRequest()
            }))
        }
        .sheet(isPresented: $needAbout) {
            AboutUsView()
        }
    }
    
    func destinationView(for item: Todo) -> some View {
        if item.name == "权限设置" {
//            return AnyView(AuthSeetingView())
        }else if item.name == "乘客信息" {
            return AnyView(PassengerFullInfoView(passenger: self.passengerInfo))
        }else if item.name == "用户反馈"{
//            return AnyView(FeedbackView())
        } else if item.name == "隐私政策" {
//            return AnyView(PrivacyAgreement())
        } else if item.name == "我的订单" {
            return AnyView(OrdersView())
        } else if item.name == "日志查看" {
            return AnyView(LogView())
        } else if item.name == "关于我们" {
            return AnyView(AboutUsView())
        }
        else{
//            return AnyView(EmptyView())
        }
        return AnyView(EmptyView())
    }
    
    func cellTectView(for item: Todo) -> some View {
        
        if item.name == "权限设置" {
            
            return Text("权限设置")
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
            
        } else if item.name == "乘客信息" {
            return Text("乘客信息")
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
            
        } else if item.name == "应用设置" {
            return Text("应用设置")
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
            
        } else if item.name == "屏幕方向" {
            return Text("屏幕方向")
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
            
        } else if item.name == "设置语言" {
            return Text("设置语言")
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
            
        } else if item.name == "用户反馈"{
            return Text("用户反馈")
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
        } else if item.name == "隐私政策" {
            return Text("隐私政策")
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
        } else if item.name == "我的订单" {
            return Text("我的订单")
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
        } else if item.name == "注销账号" {
            return Text("注销账号")
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
        } else if item.name == "软件版本" {
            return Text("软件版本")
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
        } else if item.name == "日志查看" {
            return Text("日志查看")
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
        }else if item.name == "关于我们" {
            return Text("关于我们")
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
        }
        else {
            return Text(item.name)
                .offset(x:0, y: 0)
                .font(.system(size: 16) .bold())
                .foregroundColor(Color(hex: 0x333333))
        }
    }
    

    
    
    func quitAletView() {
        
        let alertController = UIAlertController(title: "注销",
                                                message: "注销账号服务器将删除账号和所有数据，无法恢复，彻底删除的话请点击确定！", preferredStyle: .alert)
        let cancelTitle = NSMutableAttributedString(string: "取消")
        cancelTitle.addAttribute(NSAttributedString.Key.foregroundColor, value: Color(hex: 0x85308D), range: NSRange(location: 0, length: cancelTitle.length))
        let cancelAction = UIAlertAction(title: "取消", style: .destructive, handler: nil)
        
        //修改颜色崩溃
        //                                    cancelAction.setValue(Color(hex: 0x85308D), forKey: "_titleTextColor")
        
        let okAction = UIAlertAction(title: String(localized: "确定"), style: .default, handler: {
            action in
            self.unregistRequest()
        })
        
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        
        if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
            // 当前控制器为rootViewController或者其子控制器
            let currentViewController = rootViewController
            // 使用currentViewController进行后续操作
            currentViewController.present(alertController, animated: true, completion: nil)
        }
    }
    
    func unregistRequest() {
        
        let openId = Singleton.shared.openId
//        Api.unregistApi(openId: openId) { r in
//            self.show = false
//            switch r {
//               case .success(let data):
//                logger.info("data:\(data)")
//                self.successShow.toggle()
//    
//               case .failure(let err):
//                
//                self.errorStr = err.localizedDescription
//                self.errorShow.toggle()
//                logger.info("error:\(err.localizedDescription)")
//            }
//        }
    }
}

//struct SettingView_Previews: PreviewProvider {
//
//    static var previews: some View {
//        SettingView()
//    }
//}


struct Todo {
    let icon: String
    let name: String
    let url: String
    let index: Int
    let push: Bool
    let value: String
}
